import { UploadImageApi } from '@/api/testUpload'
export class UploadImage {
  constructor(file) {
    this.chunkSize = 1024 * 300 // *M
    this.chunks = Math.ceil(file.size / this.chunkSize)
    this.requestList = []
    this.chunkList(file)
  }
  chunkList(file) {
    for (let i = 0; i < this.chunks; i++) {
      this.requestList.push(this.upload(i, file))
    }
  }
  // 上传chunk
  upload(i, file) {
    return new Promise((resovle, reject) => {
      var end = (i + 1) >= this.chunks ? file.size : (i + 1) * this.chunkSize
      var form = new FormData()
      form.append('data', file.slice(i * this.chunkSize, end)) // file对象的slice方法用于切出文件的一部分
      form.append('total', this.chunks) // 总片数
      form.append('index', i) // 当前是第几片
      UploadImageApi(form).then(res => {
        resovle(res)
      }).catch(rej => {
        reject(rej)
      })
    })
  }
}
